<route lang="json5" type="home">
{
  layout: 'tabbar',
  style: {
    // 'custom' 表示开启自定义导航栏，默认 'default'
    navigationStyle: 'custom',
    navigationBarTitleText: '首页',
  },
}
</route>

<script lang="ts" setup>
import type { BannerItem, CategoryItemDto } from '@/service/app'
import { BASE_URL } from '@/constants'
import { bannerControllerFindAll as getBanner, categoryControllerGetRecommendList as getCategoryAPI, guideControllerFindAll as getGuideAPI } from '@/service/app'
import { useUserStore } from '@/store'

defineOptions({
  name: 'Home',
})

// 获取屏幕边界到安全区域距离
let safeAreaInsets
let systemInfo

// #ifdef MP-WEIXIN
// 微信小程序使用新的API
systemInfo = uni.getWindowInfo()
safeAreaInsets = systemInfo.safeArea
  ? {
      top: systemInfo.safeArea.top,
      right: systemInfo.windowWidth - systemInfo.safeArea.right,
      bottom: systemInfo.windowHeight - systemInfo.safeArea.bottom,
      left: systemInfo.safeArea.left,
    }
  : null
// #endif

// #ifndef MP-WEIXIN
// 其他平台继续使用uni API
systemInfo = uni.getSystemInfoSync()
safeAreaInsets = systemInfo.safeAreaInsets
// #endif
const author = ref('余庆')
// 测试 uni API 自动引入

const userStore = useUserStore()
const guideList = ref([])
const playType = ref<CategoryItemDto[]>()
// 背景轮播图相关
const current = ref<number>(0)

const indicator: any = { type: 'dots-bar' }

const backList = ref<BannerItem[]>([
  {
    cover: 'https://m.360buyimg.com/i/jfs/t1/313743/2/14529/72956/686777b3F541a188c/1017aab5a87a3f64.jpg',
    title: '111',
    type: 'ARTICLE',
    articleUrl: 'https://www.baidu.com',
    id: 1,
    createdAt: '2023-08-01',
    updatedAt: '2023-08-01',
  },
  {
    cover: 'https://m.360buyimg.com/i/jfs/t1/287170/5/14892/176740/686777b6F515facd1/f96ff12c4b26b84e.jpg',
    title: '222',
    type: 'ARTICLE',
    articleUrl: 'https://www.baidu.com',
    id: 2,
    createdAt: '2023-08-01',
    updatedAt: '2023-08-01',
  },
])
onLoad(async () => {
  console.log('项目作者:', author.value)

  try {
    // 获取攻略列表
    const guideData = await getGuideAPI({ })
    console.log('guideData:', guideData) // 确认数据结构
    guideList.value = guideData.data || [] // 添加默认值防止 undefined

    // 获取分类列表
    const categoryResponse = await getCategoryAPI({ })
    console.log('categoryResponse:', categoryResponse) // 确认数据结构
    playType.value = categoryResponse.data || [] // 添加默认值防止 undefined

    // 获取banner列表
    const bannerResponse = await getBanner({ })
    console.log('bannerResponse:', bannerResponse) // 确认数据结构
    backList.value = (bannerResponse.data || []).map(item => ({
      ...item, // 保留原有属性
      cover: BASE_URL + item.cover, // 拼接完整URL
    }))
  }
  catch (error) {
    console.error('数据获取失败:', error)
  }
})

// 开屏动画控制
const showSplash = ref(true) // 控制容器是否存在
const splashOpacity = ref(1) // 控制透明度（用于渐隐效果）
const splashGif = ref('https://img.meituan.net/csc/fd5f5bcbcbaed21316d9738cc92e47017898172.gif')

onLoad(async () => {
  uni.hideTabBar()
  // 重置状态（确保每次进入首页都重新显示动画）
  showSplash.value = true
  splashOpacity.value = 1

  // 2秒后开始渐隐
  setTimeout(() => {
    // 触发渐隐（0.5秒过渡到透明）
    splashOpacity.value = 0
    // 等渐隐完成后（0.5秒）再隐藏容器并显示tabBar
    setTimeout(() => {
      showSplash.value = false
      uni.showTabBar()
    }, 500)
  }, 2000)
})

function handleClick(e) {
  console.log(e)
}
function onChange(e) {
  // console.log(e)
}

// grid对象定义
const grid = [
  {
    icon: '/static/images/1官方商城.png',
    text: '官方商城',
    url: '/pages/goods/index',
  },
  {
    icon: '/static/images/2时节鉴赏.png',
    text: '时节鉴赏',
    url: '/pages/mine/seasonal',
  },
  {
    icon: '/static/images/3交通向导.png',
    text: '交通向导',
    url: '/pages/index/traffic',
  },
  {
    icon: '/static/images/4好吃好玩.png',
    text: '好吃好玩',
    url: '/pages/delicious/delicious',
  },
  {
    icon: '/static/images/5市集文创.png',
    text: '市集文创',
    url: '',
  },
  {
    icon: '/static/images/6研学活动.png',
    text: '研学活动',
    url: '/pages/index/studyTour',
  },
  {
    icon: '/static/images/7咨询热线.png',
    text: '咨询热线​',
    url: '/pages/index/hotLine',
  },
  {
    icon: '/static/images/8油车港介绍.png',
    text: '油车港​介绍​',
    url: '/pages/index/introduce',
  },
]

// 金刚区页面跳转
function goPage(url) {
  if (url === '/pages/goods/index') {
    // 当 url 为 tabbar 页面时，使用 uni.switchTab 跳转
    uni.switchTab({
      url,
      fail: (err) => {
        console.error('跳转失败', err)
      },
    })
  }
  else if (url) {
    // 其他有效 url 使用 uni.navigateTo 跳转
    uni.navigateTo({
      url,
      fail: (err) => {
        console.error('跳转失败', err)
      },
    })
  }
}

// 进入商品详情
function goShopDetail(item) {
  const url = '/pages/goods/detail'
  const id = item.id
  uni.navigateTo({
    url: `/pages/goods/detail?id=${id}`,
    success: (res) => {
      res.eventChannel.emit('acceptDataFromOpenerPage', { item })
    },
  })
}

// 进入资讯页面详情
function goNewsDetail(item) {
  const url = '/pages/news/newsDetail'
  const title = item.id
  uni.navigateTo({
    url: `/pages/news/newsDetail?id=${title}`,
    success: (res) => {
      res.eventChannel.emit('acceptDataFromOpenerPage', { item })
    },
  })
}

// 控制对话框显示状态
const showDialog = ref(false)
// 控制客服图片显示
const showKefu2 = ref(false)

// 鼠标移入事件处理函数
function handleMouseEnter() {
  showDialog.value = true
  showKefu2.value = true
}

// 鼠标移出事件处理函数
function handleMouseLeave() {
  showDialog.value = false
  showKefu2.value = false
}

// 鼠标/触摸进入事件处理函数
function handleEnter() {
  showDialog.value = true
  showKefu2.value = true
}

// 鼠标/触摸移出事件处理函数
function handleLeave() {
  showDialog.value = false
  showKefu2.value = false
}

// 浮动IP点击跳转客服页面
function goKefu() {
  uni.navigateTo({
    url: '/pages/mine/contactKefu',
  })
}

const chooseIndex = ref(0)
function handleChoose(index) {
  chooseIndex.value = index
}

// 拼团列表
const groupList = ref([
  {
    id: 1,
    name: '拼团1拼团1拼团1拼团1',
    price: 100.00,
    num: 10,
    cover: 'https://m.360buyimg.com/i/jfs/t1/306136/5/15674/110093/686777b2F2aac0155/a1b9c1b5ef5807c1.jpg',
  },
  {
    id: 2,
    name: '拼团2拼团2拼团2拼团2',
    price: 200.00,
    num: 20,
    cover: 'https://m.360buyimg.com/i/jfs/t1/306136/5/15674/110093/686777b2F2aac0155/a1b9c1b5ef5807c1.jpg',
  },
  {
    id: 3,
    name: '拼团3拼团3拼团3拼团3',
    price: 300.00,
    num: 30,
    cover: 'https://m.360buyimg.com/i/jfs/t1/306136/5/15674/110093/686777b2F2aac0155/a1b9c1b5ef5807c1.jpg',
  },
])
</script>

<template>
  <!-- class="bg-white px-4 pt-2" :style="{ marginTop: `${safeAreaInsets?.top}px` }" -->
  <!-- 开屏动画容器（修改后） -->
  <view
    v-if="showSplash"
    class="splash-container"
    :style="{ opacity: splashOpacity }"
  >
    <image
      :src="splashGif"
      mode="aspectFill"
      class="splash-gif animate-fade-in"
    />
  </view>

  <view
    class="bg-white"
  >
    <!-- 背景轮播图 -->
    <wd-swiper
      v-model:current="current" value-key="cover" :list="backList" autoplay :indicator="indicator" height="280"
      @click="handleClick" @change="onChange"
    />
    <view class="relative z-100 mt-[-70rpx] rounded-2xl bg-white p-3">
      <!-- 快捷菜单 -->
      <view class="mb-4 mt-3 box-border flex flex-wrap justify-between">
        <view v-for="(item, index) in grid" :key="index" class="w-[25%]" @click="goPage(item.url)">
          <view class="flex flex-col items-center">
            <image
              :src="item.icon" mode="aspectFit" class="h-17 w-17"
            />
            <view class="mt-2 text-center text-[28rpx]">
              {{ item.text }}
            </view>
          </view>
        </view>
      </view>
      <!-- 油车港攻略区域 -->
      <view class="mt-4 text-xl text-[#363636] font-bold tracking-[0.2em]">
        游车港攻略
      </view>
      <!-- 横向滚动的圆角矩形块 -->
      <scroll-view class="mt-4" scroll-x :show-scrollbar="false">
        <view class="flex">
          <view
            v-for="(item, index) in guideList"
            :key="index" @click="goNewsDetail(item)"
          >
            <!-- <text>{{item.title}}</text> -->
            <img :src="BASE_URL + item.cover" alt="" class="mr-4 h-[340rpx] w-[300rpx] rounded-lg">
          </view>
        </view>
      </scroll-view>

      <!-- 拼团栏 -->
      <view class="mt-4 text-xl text-[#363636] font-bold tracking-[0.2em]">
        即刻拼团·优惠尽享
      </view>
      <scroll-view scroll-x :show-scrollbar="false">
        <view class="mb-1 mt-3 flex">
          <view
            v-for="(item, index) in groupList"
            :key="index"
            class="mb-4 mr-4 w-[310rpx] rounded-lg shadow-md"
          >
            <image
              :src="item.cover"
              mode="aspectFill"
              class="relative z-[-10] h-[150rpx] w-[310rpx] rounded-tl-lg rounded-tr-lg"
            />
            <view class="p-1">
              <view class="line-clamp-1 overflow-hidden break-words text-28rpx text-[#363636]">
                {{ item?.name || '商品名' }}
              </view>
              <view class="flex items-end text-26rpx text-red">
                ￥ <view class="text-30rpx">
                  {{ item?.price || '-' }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <view class="mt-2 bg-transparent text-xl text-[#363636] font-bold tracking-[0.2em]">
        吃喝玩乐·尽享优惠
      </view>
      <!-- 吃喝玩乐商品分类 -->
      <scroll-view scroll-x :show-scrollbar="false">
        <view class="mt-3 flex">
          <view
            v-for="(item, index) in playType"
            :key="index"
            :class="{
              'bg-[#e7e0da] text-[#c1a58e]': index !== chooseIndex,
              'bg-[linear-gradient(to_right,#e0cebd,#bfa189)] text-white': index === chooseIndex,
            }"
            class="mb-40rpx mr-3 h-50rpx w-120rpx flex flex-shrink-0 items-center justify-center rounded-md px-3 text-[30rpx]"
            @click="handleChoose(index)"
          >
            {{ item.name.slice(0, 4) }}
          </view>
        </view>
      </scroll-view>
      <!-- 吃喝玩乐区块 -->
      <view class="grid grid-cols-2 gap-4">
        <view
          v-for="(item, index) in (playType && playType[chooseIndex] ? playType[chooseIndex].goods : []) || []"
          :key="index"
          class="overflow-hidden rounded-lg shadow-md"
          @click="goShopDetail(item)"
        >
          <image :src="BASE_URL + item?.cover" mode="aspectFill" class="h-[180px] w-full" />
          <view class="p-3">
            <view class="line-clamp-2 mb-1 overflow-hidden break-words text-base text-[#363636]">
              {{ item?.title || '商品名' }}
            </view>
            <view class="flex text-lg">
              ￥ <view class="text-38rpx">
                {{ item?.minPrice || '-' }}
              </view>
            </view>
          </view>
        </view>
      </view>
      <DefaultPlaceholder v-if="playType && playType[chooseIndex] && playType[chooseIndex].goods && playType[chooseIndex].goods.length === 0" image-src="https://m.360buyimg.com/i/jfs/t1/317766/35/15395/4445/687096ffF2248d0f3/801f828814997031.jpg" :text="`暂无${(playType && playType[chooseIndex] ? playType[chooseIndex].name : '类型')}的商品`" />
      <!-- 客服区域 -->
      <view class="fixed bottom-40 right-2 z-2000 flex items-center">
        <!-- 延伸对话框 -->
        <view v-if="showDialog" class="relative mr-3 rounded-lg bg-white p-2 shadow-md">
          <view class="text-[28rpx] text-[#bfa18a]">
            点击了解，游玩攻略
          </view>
          <!-- 三角形箭头 -->
          <view
            class="arrow"
          />
        </view>
        <!-- 客服图标 -->
        <view
          @click="goKefu"
          @mouseenter="handleMouseEnter"
          @mouseleave="handleMouseLeave" @touchstart="handleEnter" @touchend="handleLeave"
        >
          <image :src="showKefu2 ? 'https://img.meituan.net/csc/fc29031a92512466a312b3d466d68f8510049806.gif' : '/static/images/kefu01.png'" mode="aspectFit" class="h-20 w-16" />
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped>
/* 开屏动画样式（修改后） */
.splash-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  /* 关键：添加过渡效果，让opacity变化平滑 */
  transition: opacity 0.5s ease-out;
}

.splash-gif {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 淡入动画（保持不变） */
.animate-fade-in {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

/* 附动IP提示框三角形箭头样式 */
.arrow {
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-left: 8px solid white;
  position: absolute;
  right: -7px;
  /* 确保箭头在对话框右侧边缘 */
  top: 40%;
  transform: translateY(-50%);
}

/* 隐藏微信小程序滚动条 */
scroll-view::-webkit-scrollbar {
  width: 0;
  height: 0;
  display: none;
}

/* 滚动条隐藏 */
::v-deep ::-webkit-scrollbar {
  height: 0;
  width: 0 !important;
  color: transparent;
}
</style>
